<template>
    <!-- 流量采集  -->
    <div id="hwTargetAllot">
        <div class="targetHeader">
            <Button type="primary" ghost @click="showAddAndUpdate" style="margin-right: 15px">
                <Icon type="md-add" />
                添加任务
            </Button>
            <!-- :disabled="accessGroupList.length == 0 || disabledAllBtn" -->
            <Input
                v-model.trim="query.name"
                placeholder="名称"
                clearable
                style="width: 180px; margin-right: 15px"
                @on-change="changePage(1)"
            ></Input>
            <Page
                :total="totalCount"
                show-total
                show-elevator
                @on-page-size-change="changeSize"
                :current="query.pageIndex"
                @on-change="changePage"
                style="float: right"
            >
            </Page>
        </div>
        <Table :columns="column" :data="dataList"></Table>
        <Modal
            v-model="targetModal.show"
            :title="targetModal.title"
            :loading="targetModal.loading"
            width="700"
            class="account-target-modal"
            :mask-closable="false"
            @on-visible-change="modalVisibleChange"
            @on-ok="handleSubmit('formValidate')"
            @on-cancel="closeTargetModal('formValidate')"
        >
            <Form ref="formValidate" :model="formValidate" :rules="ruleValidate" :label-width="80">
                <FormItem label="名称" prop="name">
                    <Input
                        v-model="formValidate.name"
                        :placeholder="nameErrorTip"
                        clearable
                        :maxlength="64"
                    ></Input>
                </FormItem>
                <!-- <FormItem label="类型" prop="taskMode">
                    <RadioGroup v-model="formValidate.taskMode">
                        <Radio label="normal">流程任务</Radio>
                        <Radio label="preset">预设临机任务</Radio>
                    </RadioGroup>
                </FormItem> -->
                <FormItem label="协议" prop="metadata" style="position: relative">
                    <Select filterable v-model="formValidate.metadata" placeholder="协议" clearable>
                        <!-- <Option value="">不选择协议</Option> -->
                        <Option value="1">ICMP</Option>
                        <Option value="6">TCP</Option>
                        <Option value="17">UDP</Option>
                        <!-- <Option
                            v-for="(item, index) in appProtocolsList"
                            :value="item"
                            :key="index"
                        >
                            {{ item }}
                        </Option> -->
                    </Select>
                </FormItem>
                <FormItem v-model="formValidate.selectedVmData" label="端口">
                    <span class="starlet">*</span>
                    <input type="hidden" />
                    <div class="flex-wrap">
                        <Tag
                            v-for="item in formValidate.selectedVmData"
                            :key="`${item.id}-${item.name}`"
                            :name="item.id"
                            closable
                            @on-close="handleClose2"
                            color="primary"
                            type="dot"
                            >{{ item.name }}-{{ item.ip }}</Tag
                        >
                    </div>
                </FormItem>
                <div style="text-align: right">
                    <Button type="primary" @click="addSelectedData" style="margin-right: 17px"
                        >添加</Button
                    >
                    <Input
                        placeholder="请输入设备名称"
                        style="width: 210px"
                        v-model="formValidate.vmName"
                        clearable
                    ></Input>
                    <Input
                        placeholder="请输入IP"
                        style="width: 210px"
                        v-model="formValidate.vmIP"
                        clearable
                    ></Input>
                    <Button type="primary" @click="refreshVmList" style="margin-left: 5px"
                        >搜索</Button
                    >
                </div>
                <Table
                    border
                    :columns="columnsVmList"
                    :data="dataVmList"
                    style="margin-top: 10px"
                    @on-selection-change="getSelectedData"
                ></Table>
                <Page
                    :total="vmTotal"
                    :current="vmCurrentPage"
                    :page-size="vmItemPage"
                    :show-total="true"
                    @on-change="switchineVmCurrentPage"
                    @on-page-size-change="switchVmItemPage"
                    class-name="pageStyleVm"
                >
                </Page>
                <!-- <FormItem label="属性">
          <cusAttribute
            ref="cusAttribute"
            @func="getMsgFormSon"
            v-bind:msgVal="propertiesData"
          ></cusAttribute>
        </FormItem> -->
                <!-- <FormItem label="描述" prop="desc" style="margin-top: 10px">
                    <Input
                        v-model="formValidate.desc"
                        type="textarea"
                        :autosize="{ minRows: 2, maxRows: 5 }"
                        placeholder="请输入内容"
                        clearable
                        :maxlength="200"
                    ></Input>
                </FormItem> -->
            </Form>
        </Modal>

        <Modal v-model="taskDeailModal" title="任务启动详情" width="80%" :mask-closable="false">
            <Table
                border
                ref=""
                :columns="taskDeailColumns"
                :data="taskDeailData"
                @on-expand="hostDeail"
            ></Table>
        </Modal>
    </div>
</template>

<script>
// import CardList from '@/components/list-template/card-list/cardList.vue';
import { debounce } from '@/libs/utils';
// import { categoryMixin } from '../hw/mixins';
import {
    queryTaskList,
    delTask,
    taskDetailHis,
    deployedPortsInfo,
    operateExecute,
    addTask,
    updateTask,
    deployedProjectsList,
    getTaskDetail,
} from '../api/process/task';
import { validateName1, nameErrorTip } from '@/libs/reg';
import { appProtocols } from '@/api/integration3d';
// import {validateNameCNLU,taskMixin } from './taskMixin'
// const validateNameCNLU = (rule, value, callback) => {
//     var myReg = /[~!！@#$%^&*()/\|,<>?"'“‘();:+=\[\]{}]/;
//     value = value.replace(/\s*/g, '');
//     if (!value) {
//         callback('请填写名称');
//     } else {
//         if (myReg.test(value)) {
//             callback('名称不能包含特殊字符');
//         } else {
//             callback();
//         }
//     }
// };
export default {
    name: 'trafficCollection',
    props: ['disabledAllBtn', 'prjId', 'sceneId'],
    // components: { CardList },
    // mixins: [categoryMixin],
    data() {
        // const validateNum = (rule, value, callback) => {
        //     //验证只能填入数字
        //     var reg = new RegExp('^([1-9]|[1-9]\\d|100)$');
        //     //验证警戒值
        //     if (value) {
        //         if (!reg.test(value)) {
        //             callback(new Error('请输入1-100的整数'));
        //         } else {
        //             callback();
        //         }
        //     } else {
        //         callback();
        //     }
        // };
        return {
            nameErrorTip,
            teamName: '',
            targetModal: {
                show: false,
                title: '采集任务',
                loading: true,
                type: 1, //1添加，2修改
            },
            judgePanelType: true, //判断是修改还是保存
            workingAreaTaskId: '', //存放修改的任务id
            modifyTargetModal: {
                show: false,
                title: '修改分配',
                loading: true,
            },
            accessGroupList: [],
            vmlists: [],
            allVms: [],
            query: {
                pageIndex: 1,
                pageSize: 10,
                projectId: this.prjId,
                sceneId: this.sceneId,
            },
            questionList: [],
            formValidate: {
                name: '',
                metadata: '',
                Profile: '',
                osInfo: '',
                type: '',
                configContent: '',
                selectedVmData: [],
                desc: '',
                vmName: '',
                vmIP: '',
                taskMode: 'preset',
            },
            ruleValidate: {
                name: [
                    { required: true, message: '', trigger: 'change', validator: validateName1 },
                ],
                // metadata: [
                //   { required: false, message: '请选择协议', trigger: 'change' },
                // ],
                selectedVmData: [{ required: true, message: '请选择端口', trigger: 'change' }],
                taskMode: [{ required: true, message: '', trigger: 'blur' }],
            },
            allotFormValidate: {
                createTime: '',
                externalIp: '',
                externalPort: '',
                externalServicePort: '',
                id: '',
                sceneId: '',
                subnetId: '',
                subnetName: '',
                targetId: '',
                targetName: '',
                teamId: '',
                teamName: '',
                visibility: 0,
                vmId: '',
                vmName: '',
            },
            column: [
                // {
                //     type: 'selection',
                //     width: 60,
                //     align: 'center',

                // },
                // {
                //     title:'任务ID',
                //     key:'id',
                //     align:'center'
                // },
                {
                    title: '名称',
                    key: 'name',
                    // align: 'center',
                    ellipsis: true,
                    tooltip: true,
                    placement: 'top-left',
                    minWidth:100
                    // width: 240,
                },
                // {
                //   title: '创建人',
                //   key: 'creator',
                //   align: 'center',
                //   ellipsis: true,
                //   tooltip: true,
                //   width: 100,
                //   placement: 'top-left'
                // },
                {
                    title: '创建时间',
                    key: 'created',
                    // align: 'center',
                    ellipsis: true,
                    width: 180,
                    tooltip: true,
                },

                {
                    title: '状态',
                    key: 'status',
                    align: 'center',
                    // width: 130,
                    minWidth:100,
                    render: (h, params) => {
                        let obj = this.setStatusType(params.row.status);
                        return h(
                            'Tag',
                            {
                                props: {
                                    color: obj.color,
                                },
                            },
                            obj.str
                        );
                    },
                },
                {
                    title: '协议',
                    key: 'metadata',
                    // align: 'center',
                    // width: 100,
                    minWidth:100,
                    render: (h, params) => {
                        let metadataObj = params.row.metadata || {};
                        let protoNum =
                            metadataObj.proto === '-1' || !metadataObj.proto
                                ? '-'
                                : metadataObj.proto;
                        // let text = '';
                        // if (protoNum == 1) {
                        //     text = 'ICMP';
                        // } else if (protoNum == 6) {
                        //     text = 'TCP';
                        // } else if (protoNum == 17) {
                        //     text = 'UDP';
                        // }
                        return h('div', protoNum);
                    },
                },
                {
                    title: '详情',
                    key: 'overview',
                    // align: 'center',
                    minWidth:100,
                    render: (h, params) => {
                        let statics = params.row.overview;
                        let statusGroup = [];
                        if (JSON.stringify(statics) != '{}') {
                            for (let i in statics) {
                                let text = '';
                                switch (i) {
                                    case 'running':
                                        text = '运行中';
                                        break;
                                    case 'error':
                                        text = '失败';
                                        break;
                                    case 'failed':
                                        text = '失败';
                                        break;
                                    case 'completed':
                                        text = '完成';
                                        break;
                                    case 'initialized':
                                        text = '初始化';
                                        break;
                                    case 'starting':
                                        text = '启动中';
                                        break;
                                    case 'closing':
                                        text = '关闭中';
                                        break;
                                    default:
                                        text = i;
                                        break;
                                }
                                statusGroup.push(h('p', {}, text + ':' + statics[i]));
                            }
                        }
                        return h('div', {}, statusGroup);
                    },
                },
                // {
                //     title: '任务种类',
                //     key: '',
                //     align: 'center',
                //     render: (h, params) => {
                //         let _text = null;
                //         if (params.row.taskMode == 'normal') {
                //             _text = '流程任务';
                //         } else if (params.row.taskMode == 'temp') {
                //             _text = '实时任务';
                //         } else {
                //             _text = '预设临机任务';
                //         }
                //         return h('div', {}, _text);
                //     },
                // },
                {
                    title: '操作',
                    key: '-',
                    // align: 'center',
                    width: 360,
                    placement: 'top-right',
                    action: true,
                    render: (h, params) => {
                        let _this = this;
                        let taskStatus = this.getStatusColor(params.row.status).taskStatus;
                        let taskBtnType = this.getStatusColor(params.row.status).taskBtnType;
                        let disabled = false;
                        if (params.row.taskMode == 'normal') {
                            disabled = true;
                        } else {
                            disabled = false;
                        }
                        return h('div', [
                            h(
                                'Poptip',
                                {
                                    props: {
                                        confirm: true,
                                        title: '您确定要删除此任务吗？',
                                        transfer: true,
                                    },
                                    on: {
                                        'on-ok': () => {
                                            this.deleteTask(params.row.id);
                                        },
                                        'on-cancel': () => {},
                                    }
                                },
                                [
                                    h(
                                        'Button',
                                        {
                                            props: {
                                                type: 'error',
                                                size: 'small',
                                                disabled: disabled,
                                            },
                                            attrs: {
                                                title: '删除',
                                            },
                                            style: {
                                                // border: 'none',
                                                // background: 'none',
                                                // boxShadow: 'none',
                                            },
                                        },
                                        '删除任务'
                                        // [
                                        //     h('img', {
                                        //         attrs: {
                                        //             src: disabled
                                        //                 ? require('@/assets/mainImage/delNote-d.png')
                                        //                 : require('@/assets/mainImage/delNote-h.png'),
                                        //         },
                                        //         style: {
                                        //             cursor: 'pointer',
                                        //             //				                            'margin-right':'5px',
                                        //             'vertical-align': 'middle',
                                        //             //				                            width:'16px',
                                        //             //				                            height:'auto',
                                        //             display: 'inline-block',
                                        //             marginBottom: '4px',
                                        //         },
                                        //     }),
                                        // ]
                                    ),
                                ]
                            ),
                            h(
                                'Button',
                                {
                                    props: {
                                        type: 'primary',
                                        size: 'small',
                                        disabled: this.disabledAllBtn,
                                    },
                                    attrs: {
                                        title: '修改',
                                    },
                                    class:'ml10',
                                    style: {
                                        // border: 'none',
                                        // background: 'none',
                                        // boxShadow: 'none',
                                    },
                                    on: {
                                        click: () => {
                                            this.updateTask(params.row.id);
                                        },
                                    },
                                },
                                '修改任务'
                                // [
                                //     h('img', {
                                //         attrs: {
                                //             src: disabled
                                //                 ? require('@/assets/mainImage/modifys.png')
                                //                 : require('@/assets/mainImage/modifys-h.png'),
                                //         },
                                //         style: {
                                //             cursor: 'pointer',
                                //             //			                            'margin-right':'5px',
                                //             'vertical-align': 'middle',
                                //             //			                            width:'16px',
                                //             //			                            height:'auto',
                                //             display: 'inline-block',
                                //             marginBottom: '4px',
                                //         },
                                //     }),
                                // ]
                            ),
                            h(
                                'Poptip',
                                {
                                    props: {
                                        confirm: true,
                                        title: '您确定要' + taskStatus + '此任务吗？',
                                        transfer: true,
                                    },
                                    on: {
                                        'on-ok': () => {
                                            _this.activeTask(params.row.id, taskStatus);
                                        },
                                        'on-cancel': () => {},
                                    },
                                    class:'ml10',
                                },
                                [
                                    h(
                                        'Button',
                                        {
                                            props: {
                                                type:taskBtnType,
                                                // type: 'success',
                                                size: 'small',
                                                disabled: disabled,
                                            },
                                            title: {
                                                title: taskStatus + '任务',
                                            },
                                            style: {
                                                // border: 'none',
                                                // background: 'none',
                                                // boxShadow: 'none',
                                                // display:btnStyle
                                            },
                                        },
                                        `${taskStatus}任务`
                                        // [
                                        //     h('img', {
                                        //         attrs: {
                                        //             src:
                                        //                 taskStatus == '停止'
                                        //                     ? disabled
                                        //                         ? require('@/assets/globalIcon/dis-stop-task.png')
                                        //                         : require('@/assets/globalIcon/stop-task.png')
                                        //                     : disabled
                                        //                     ? require('@/assets/globalIcon/dis-start-task.png')
                                        //                     : require('@/assets/globalIcon/start-task.png'),
                                        //         },
                                        //         style: {
                                        //             cursor: 'pointer',
                                        //             'vertical-align': 'middle',
                                        //             display: 'inline-block',
                                        //             marginBottom: '4px',
                                        //         },
                                        //     }),
                                        // ]
                                    ),
                                ]
                            ),
                            h(
                                'Button',
                                {
                                    props: {
                                        type: 'primary',
                                        size: 'small',
                                        // style:{margin:'10px'}
                                    },
                                    style: {
                                        // border: 'none',
                                        // background: 'none',
                                        // boxShadow: 'none',
                                    },
                                    class:'ml10',
                                    on: {
                                        click: () => {
                                            _this.taskDeail(params.row.id);
                                        },
                                    },
                                },'任务详情'
                                // [
                                //     h('img', {
                                //         attrs: {
                                //             src: require('@/assets/globalIcon/magnifier-h.png'),
                                //         },
                                //         style: {
                                //             cursor: 'pointer',
                                //             //			                            'margin-right':'5px',
                                //             'vertical-align': 'middle',
                                //             //			                            width:'16px',
                                //             //			                            height:'auto',
                                //             display: 'inline-block',
                                //             marginBottom: '4px',
                                //         },
                                //     }),
                                // ]
                            ),
                        ]);
                    },
                },
            ],
            projectInfo: {},
            subnetList: [],
            networkId: '',
            idwithName: {},
            dataList: [],
            totalCount: 0,
            targetTeamDataCopy: [],
            companyList: [], //所有单位列表
            configurationData: [],
            selectedDataConfiger: [],
            selectedVmDataTable: [],
            dataVmList: [],
            vmCurrentPage: 1,
            vmItemPage: 10,
            vmTotal: 0,
            columnsVmList: [
                {
                    type: 'selection',
                    width: 60,
                    align: 'center',
                },
                {
                    title: '设备名称',
                    key: 'deviceName',
                    align: 'center',
                    ellipsis: true,
                    tooltip: true,
                },
                {
                    title: '端口名称',
                    key: 'name',
                    align: 'center',
                    ellipsis: true,
                    tooltip: true,
                },
                {
                    title: 'IP',
                    key: 'IP',
                    align: 'center',
                    render: (h, params) => {
                        let value = params.row.IP;
                        let oIP_ = [];
                        value.forEach((item, i) => {
                            oIP_.push(
                                h(
                                    'p',
                                    {
                                        color: '#000',
                                    },
                                    item
                                )
                            );
                        });
                        return h('div', oIP_);
                    },
                },
                {
                    title: '添加',
                    key: 'add',
                    align: 'center',
                    width: 80,
                    render: (h, params) => {
                        return h(
                            'Button',
                            {
                                props: {
                                    type: 'primary',
                                },
                                on: {
                                    click: (e) => {
                                        if (this.selectedVmDataTable.indexOf(params.row.id) != -1) {
                                            this.$Message.info('已添加');
                                            return;
                                        }
                                        this.addVmAfterTable(params.row);
                                        this.selectedVmDataTable.push(params.row.id);
                                        let oIP_ = '';
                                        params.row.IP.forEach((i, item) => {
                                            if (oIP_ == '') {
                                                oIP_ = item;
                                            } else {
                                                oIP_ += ',' + item;
                                            }
                                        });
                                        this.formValidate.selectedVmData.push({
                                            name: params.row.name,
                                            id: params.row.id,
                                            ip: oIP_,
                                        });
                                    },
                                },
                            },
                            '+'
                        );
                    },
                },
            ],

            //查看详情面板
            taskDeailModal: false,
            taskDeailData: [],
            taskDeailColumns: [
                {
                    type: 'expand',
                    width: '30',
                    render: (h, params) => {
                        return h('div', {}, [
                            h('Row', { props: { class: 'expand-row' } }, [
                                h('Col', { props: { span: '8' }, style: { width: '50%' } }, [
                                    h('span', { props: { class: 'expand-key' } }, 'deviceName:  '),
                                    h(
                                        'span',
                                        { props: { class: 'expand-value' } },
                                        params.row.belongDeviceName
                                    ),
                                ]),
                                h('Col', { props: { span: '8' }, style: { width: '50%' } }, [
                                    h('span', { props: { class: 'expand-key' } }, 'IP:  '),
                                    h('span', { props: { class: 'expand-value' } }, params.row.ip),
                                ]),
                            ]),
                            h('Row', { props: { class: 'expand-row' } }, [
                                h('Col', { props: { span: '8' }, style: { width: '50%' } }, [
                                    h('span', { props: { class: 'expand-key' } }, 'cidr:  '),
                                    h(
                                        'span',
                                        { props: { class: 'expand-value' } },
                                        params.row.cidr
                                    ),
                                ]),
                                h('Col', { props: { span: '8' }, style: { width: '50%' } }, [
                                    h('span', { props: { class: 'expand-key' } }, 'mac:  '),
                                    h('span', { props: { class: 'expand-value' } }, params.row.mac),
                                ]),
                            ]),
                            h('Row', { props: { class: 'expand-row' } }, [
                                h('Col', { props: { span: '8' }, style: { width: '50%' } }, [
                                    h('span', { props: { class: 'expand-key' } }, 'cloudId:  '),
                                    h(
                                        'span',
                                        { props: { class: 'expand-value' } },
                                        params.row.osId
                                    ),
                                ]),
                                h('Col', { props: { span: '8' }, style: { width: '50%' } }, [
                                    h('span', { props: { class: 'expand-key' } }, 'hostIP:  '),
                                    h(
                                        'span',
                                        { props: { class: 'expand-value' } },
                                        params.row.hostIp
                                    ),
                                ]),
                            ]),
                        ]);
                    },
                },
                {
                    title: '名称',
                    key: 'deviceName',
                    align: 'center',
                },
                {
                    title: '状态',
                    key: 'status',
                    align: 'center',
                    render: (h, params) => {
                        let obj = this.setStatusType(params.row.status);
                        return h(
                            'Tag',
                            {
                                props: {
                                    color: obj.color,
                                },
                            },
                            obj.str
                        );
                    },
                },
                {
                    title: '创建时间',
                    key: 'created',
                    align: 'center',
                },
                {
                    title: '更新时间',
                    key: 'updated',
                    align: 'center',
                },
                {
                    title: '信息',
                    key: 'message',
                    align: 'center',
                },
            ],
            properties: {},
            propertiesData: [],
            appProtocolsList: [],
        };
    },
    async mounted() {
        this.queryTaskList();
    },
    methods: {
        getMsgFormSon(data) {
            this.propertiesData = data;
        },
        // 删除任务采集任务
        deleteTask(id) {
            delTask(id)
                .then((res) => {
                    if (res.code == 1) {
                        this.$Message.success('删除成功');
                        this.queryTaskList();
                    } else {
                        this.$Message.warning('删除失败');
                    }
                })
                .catch((error) => {
                    this.$Message.error(error);
                });
        },

        // 开始，结束
        activeTask(id, active) {
            let op;
            if (active == '开始') {
                op = 'start';
            } else if (active == '停止') {
                op = 'stop';
            }
            operateExecute(id, op)
                .then((res) => {
                    if (res.code == 1) {
                        this.$Message.success(active + '任务成功');
                        this.queryTaskList();
                    } else {
                        this.$Message.error(res.message);
                    }
                })
                .catch((error) => {
                    this.$Message.error(error);
                });
        },

        // 初始化
        initTask(row, init) {
            const { id: taskId, status } = row;
            if (status == 'initialized' || status == 'completed' || status == 'failed') {
                operateExecute(taskId, init)
                    .then((res) => {
                        if (res.code == 1) {
                            this.$Message.success('初始化任务成功');
                            this.queryTaskList();
                        } else {
                            this.$Message.error(res.message);
                        }
                    })
                    .catch((error) => {
                        this.$Message.error(error);
                    });
            } else {
                this.$Message.info('非完成,失败,初始化状态下不可操作');
                return;
            }
        },

        // 查看详情
        taskDeail(id) {
            taskDetailHis(id)
                .then((res) => {
                    if (res.code == 1) {
                        this.taskDeailData = [];
                        this.taskDeailModal = true;
                        res.data.forEach((item) => {
                            this.taskDeailData.push({
                                deviceName: item.deviceName,
                                status: item.status,
                                message: item.message,
                                deviceId: item.deviceId,
                                mac: '',
                                hostIp: '',
                                cidr: '',
                                osId: '',
                                ip: '',
                                belongDeviceName: '',
                                created: item.created ? item.created : '',
                                updated: item.updated ? item.updated : '',
                                _expanded: false,
                            });
                        });
                    } else {
                        this.taskDeailData = [];
                        this.taskDeailModal = true;
                    }
                })
                .catch((error) => {
                    this.$Message.error(error);
                });
        },

        // 详情信息折叠信息
        hostDeail(row) {
            if (!row._expanded) {
                deployedPortsInfo(row.deviceId).then((res) => {
                    if (res.code == 1) {
                        this.taskDeailData.forEach((item) => {
                            if (row.deviceId == item.deviceId) {
                                item._expanded = true;
                                let ipsGroup = [];
                                let cidrGroup = [];
                                if (res.data.ips && res.data.ips.length != 0) {
                                    for (let index = 0; index < res.data.ips.length; index++) {
                                        const element = res.data.ips[index];
                                        ipsGroup.push(element.ipAddress);
                                        cidrGroup.push(element.cidr);
                                    }
                                }
                                item.cidr = cidrGroup;
                                item.hostIp = res.data.hostIp;
                                item.mac = res.data.macAddress;
                                item.osId = res.data.cloudId;
                                item.ip = ipsGroup;
                                item.belongDeviceName = res.data.deviceName;
                                return false;
                            }
                        });
                    } else {
                        this.$Message.error(res.message);
                    }
                });
            } else {
                row._expanded = !row._expanded;
            }
        },
        changePage(page) {
            this.query.pageIndex = page;
            this.queryTaskList();
        },
        changeSize(size) {
            this.query.pageSize = size;
            this.queryTaskList();
        },
        // 获取列表信息
        queryTaskList(val) {
            let params = {
                testId: this.sceneId,
                // testId: '70b41c73-c02c-413f-82a3-84c89b7fe2aa',
                pageIndex: this.query.pageIndex,
                pageSize: this.query.pageSize,
                name: this.query.name,
                taskType: 'mirror_flow',
            };
            if (!params.name) {
                delete params.name;
            }
            queryTaskList(params)
                .then((res) => {
                    if (res.code == 1) {
                        this.dataList = res.data.items;
                        this.totalCount = res.data.total;
                    } else {
                        this.dataList = [];
                        this.totalCount = 0;
                    }
                })
                .catch((error) => {
                    this.$Message.error(error);
                });
        },

        // 任务状态
        setStatusType(val) {
            let obj = {
                str: '',
                color: '',
            };
            switch (val) {
                case 'running':
                    obj.str = '运行中';
                    obj.color = 'success';
                    break;
                case 'failed':
                    obj.str = '失败';
                    obj.color = 'error';
                    break;
                case 'error':
                    obj.str = '失败';
                    obj.color = 'error';
                    break;
                case 'completed':
                    obj.str = '完成';
                    obj.color = 'primary';
                    break;
                case 'initialized':
                    obj.str = '初始化';
                    obj.color = 'warning';
                    break;
                case 'starting':
                    obj.str = '启动中';
                    obj.color = 'success';
                    break;
                case 'closing':
                    obj.str = '关闭中';
                    obj.color = 'success';
                    break;
                default:
                    break;
            }
            return obj;
        },

        // 操作状态
        getStatusColor(val) {
            let obj = {
                taskStatus: null,
                taskBtnType: null,
            };
            switch (val) {
                case 'initialized':
                    obj.taskStatus = '开始';
                    obj.taskBtnType = 'success';
                    break;
                case 'error':
                    obj.taskStatus = '开始';
                    obj.taskBtnType = 'success';
                    break;
                case 'failed':
                    obj.taskStatus = '开始';
                    obj.taskBtnType = 'success';
                    break;
                case 'running':
                    obj.taskStatus = '停止';
                    obj.taskBtnType = 'error';
                    break;
                case 'completed':
                    obj.taskStatus = '开始';
                    obj.taskBtnType = 'success';
                    break;
                case 'starting':
                    obj.taskStatus = '停止';
                    obj.taskBtnType = 'error';
                    break;
                case 'closing':
                    obj.taskStatus = '停止';
                    obj.taskBtnType = 'error';
                    break;
                case 'stop_error':
                    obj.taskStatus = '停止';
                    obj.taskBtnType = 'error';
                    break;
                default:
                    break;
            }
            return obj;
        },

        // 获取采集任务端口列表数据
        deployedProjectsList() {
            let params = {
                pageIndex: this.vmCurrentPage,
                pageSize: this.vmItemPage,
                projectId: this.prjId,
                ipAddress: this.formValidate.vmIP,
                deviceName: this.formValidate.vmName,
                deviceType: 'VM',
            };
            if (!params.deviceName) {
                delete params.deviceName;
            }
            if (!params.ipAddress) {
                delete params.ipAddress;
            }
            this.dataVmList = []; // 清空一下
            deployedProjectsList(params.projectId, params)
                .then((res) => {
                    if (res.code == 1) {
                        let vmData = res.data.items;
                        this.vmTotal = res.data.total;
                        let disabled_ = false;
                        let checked_ = false;
                        vmData.forEach((item) => {
                            if (this.selectedVmDataTable.length != 0) {
                                if (this.selectedVmDataTable.indexOf(item.id) != -1) {
                                    disabled_ = true;
                                    checked_ = true;
                                } else {
                                    disabled_ = false;
                                    checked_ = false;
                                }
                            } else {
                                disabled_ = false;
                                checked_ = false;
                            }
                            let IPS = [];
                            if (item.portIps && item.portIps.length != 0) {
                                for (let index = 0; index < item.portIps.length; index++) {
                                    const element = item.portIps[index];
                                    IPS.push(element.ipAddress);
                                }
                            }
                            this.dataVmList.push({
                                name: item.name,
                                id: item.id,
                                IP: IPS,
                                _disabled: disabled_,
                                _checked: checked_,
                                deviceName: item.deviceName,
                            });
                        });
                    } else {
                        this.dataVmList = [];
                        this.vmTotal = 0;
                        this.$Message.error(data.message);
                    }
                })
                .catch((error) => {
                    this.$Message.error(error);
                });
        },
        showAddAndUpdate() {
            this.targetModal.show = true;
            this.targetModal.type = 1;
            this.formValidate.selectedVmData = [];
            this.selectedVmDataTable = [];
            this.propertiesData = [
                {
                    key: '',
                    value: '',
                },
            ];
            this.targetModal.title = '创建任务';
            this.appProtocols();
            this.deployedProjectsList();
        },
        appProtocols() {
            return;
            appProtocols()
                .then((res) => {
                    if (res.code == 1) {
                        this.appProtocolsList = res.data;
                    } else {
                        this.appProtocolsList = [];
                        this.$Message.warning(res.message);
                    }
                })
                .catch((error) => {
                    this.$Message.error(error);
                });
        },

        // 搜索
        refreshVmList() {
            this.vmCurrentPage = 1;
            this.deployedProjectsList();
        },

        getSelectedData(selection) {
            this.selectedDataConfiger = [];
            this.selectedDataConfiger = selection;
        },

        switchineVmCurrentPage(numberPage) {
            this.vmCurrentPage = numberPage;
        },
        switchVmItemPage(numberSize) {
            this.vmItemPage = numberSize;
        },

        // 添加列表数据
        addSelectedData() {
            let that = this,
                bol = true;
            that.selectedDataConfiger.forEach(function (item, i) {
                if (that.selectedVmDataTable.indexOf(item.id) != -1) {
                } else {
                    bol = false;
                    that.addVmAfterTable(item);
                    that.selectedVmDataTable.push(item.id);
                    that.formValidate.selectedVmData.push({
                        name: item.name,
                        id: item.id,
                    });
                }
            });
            if (bol) {
                that.$Message.info('请选择要添加的内容');
            }
        },

        // 取消
        closeTargetModal() {
            this.targetModal.show = false;
            this.$refs['formValidate'].resetFields();
            //	    	this.handleReset('formValidate');
            //	    	this.handleReset('addFormValidate');
        },
        // 提交
        handleSubmit(name) {
            // 属性
            this.properties = {};
            if (this.propertiesData.length != 0) {
                let attrData = this.propertiesData;
                for (let index = 0; index < attrData.length; index++) {
                    const element = attrData[index];
                    if (element.key) {
                        this.properties[element.key] = element.value;
                    }
                }
            }
            this.$refs[name].validate((valid) => {
                if (valid) {
                    if (this.selectedVmDataTable.length != 0) {
                        let params = {
                            configId: this.formValidate.configContent, // 配置
                            description: this.formValidate.desc, // 描述
                            name: this.formValidate.name,
                            deviceIdList: this.selectedVmDataTable,
                            deviceType: 'P',
                            taskType: 'mirror_flow',
                            testId: this.sceneId,
                            properties: this.properties, // 属性
                            taskMode: this.formValidate.taskMode,
                            metadata: { proto: this.formValidate.metadata || '-1' }, //协议
                        };
                        if (this.targetModal.type == 1) {
                            //判断是创建还是修改 1 为创建 2修改
                            this.saveoutbandTask(params);
                        } else {
                            this.amendTask(params);
                        }
                    } else {
                        this.$Message.info('请选择端口');
                        this.targetModal.loading = false;
                        this.$nextTick(() => {
                            this.targetModal.loading = true;
                        });
                    }
                } else {
                    this.targetModal.loading = false;
                    this.$nextTick(() => {
                        this.targetModal.loading = true;
                    });
                }
            });
        },

        saveoutbandTask(saveDateJson) {
            addTask(saveDateJson).then((res) => {
                if (res.code == 1) {
                    this.targetModal.show = false;
                    this.query.pageIndex = 1;
                    this.query.pageSize = 10;
                    this.$Message.success('添加任务成功');
                    this.queryTaskList();
                    this.targetModal.loading = false;
                    this.$nextTick(() => {
                        this.targetModal.loading = true;
                    });
                } else {
                    this.$Message.error(res.message);
                    this.targetModal.loading = false;
                    this.$nextTick(() => {
                        this.targetModal.loading = true;
                    });
                }
            });
        },

        amendTask(amendTaskData) {
            updateTask(this.workingAreaTaskId, amendTaskData).then((res) => {
                if (res.code == 1) {
                    this.query.pageIndex = 1;
                    this.query.pageSize = 10;
                    this.$Message.success('修改成功');
                    this.queryTaskList();
                    this.targetModal.show = false;
                    this.targetModal.loading = false;
                } else {
                    this.$Message.error(res.message);
                    this.targetModal.loading = false;
                    this.$nextTick(() => {
                        this.targetModal.loading = true;
                    });
                }
            });
        },

        // 修改任务
        updateTask(taskId) {
            this.formValidate.vmName = '';
            this.formValidate.vmIP = '';
            this.targetModal.title = '修改任务';
            this.targetModal.type = 2;
            this.appProtocols();
            getTaskDetail(taskId)
                .then((res) => {
                    if (res.code == 1) {
                        this.workingAreaTaskId = res.data.id;
                        this.selectedVmDataTable = [];
                        this.formValidate.selectedVmData = [];
                        this.targetModal.show = true;
                        this.propertiesData = [];
                        this.formValidate.name = res.data.name;
                        this.formValidate.desc = res.data.description;

                        this.formValidate.configContent = res.data.configId;
                        this.formValidate.metadata =
                            res.data.metadata == null ? { proto: '' } : res.data.metadata.proto;
                        if (res.data.deviceData.length != 0) {
                            res.data.deviceData.forEach((item) => {
                                this.selectedVmDataTable.push(item.deviceId);
                                this.formValidate.selectedVmData.push({
                                    name: item.deviceName,
                                    id: item.deviceId,
                                    ip: item.ip,
                                });
                            });
                        }
                        this.formValidate.taskMode = res.data.taskMode;
                        if (JSON.stringify(res.data.properties) != '{}') {
                            for (let i in res.data.properties) {
                                let obj = {};
                                obj['key'] = i;
                                obj['value'] = res.data.properties[i];
                                this.propertiesData.push(obj);
                            }
                        }
                    } else {
                        this.workingAreaTaskId = ''; //清空任务id
                        this.$Message.error(res.message);
                    }
                })
                .then(() => {
                    this.deployedProjectsList();
                    this.judgeVmStatus();
                });
        },

        judgeVmStatus() {
            let data = this.dataVmList;
            let data_ = this.selectedVmDataTable;
            data.forEach(function (item, i) {
                if (data_.indexOf(item.id) != -1) {
                    item._checked = true;
                    item._disabled = true;
                } else {
                    item._checked = false;
                    item._disabled = false;
                }
            });
        },

        handleClose2(event, name) {
            let $this = this;
            let data = this.formValidate.selectedVmData;
            $this.selectedDataConfiger = [];
            let _data = this.selectedVmDataTable;
            data.forEach(function (item, i) {
                if (item) {
                    if (item.id == name) {
                        data.splice(i, 1);
                        // _data.remove(name);
                        _data.splice(
                            $this.selectedVmDataTable.findIndex((vmId) => vmId == name),
                            1
                        );
                        $this.judgeVmStatus();
                    }
                }
            });
        },

        addVmAfterTable(param) {
            let data = this.dataVmList;
            this.dataVmList.forEach(function (item, i) {
                if (item.id == param.id) {
                    item._checked = true;
                    item._disabled = true;
                }
            });
        },

        // 模态框关闭后清空搜索条件
        modalVisibleChange(type) {},

        // 防抖封装
        getData: debounce(() => {}),
    },
};
</script>

<style scoped>
.account-target-modal >>> .starlet {
    color: red;
    position: absolute;
    left: -60px;
    font-size: 18px;
    line-height: 38px;
    font-weight: 800;
}
.account-target-modal >>> .pageStyleVm {
    text-align: center;
    margin-top: 10px;
}
.targetHeader {
    /*padding: 10px;*/
    /* margin: 15px 0px; */
    margin: 0px 0px 15px;
}
.borders {
    padding: 16px;
    background: #fff;
}
.account-target-modal /deep/ .ivu-modal .ivu-modal-content .ivu-modal-body > form {
    height: calc(100% - 65px);
    overflow: auto;
}
</style>
